﻿using System;
using System.ComponentModel;
using System.Text;
using System.Windows;
using Linq2Crm.Request;

namespace SLApp_Test
{
	public class Tracer : INotifyPropertyChanged, IDisposable
	{
		private readonly StringBuilder _builder = new StringBuilder();
		private bool wasClosed; //if true then next time clear builder

		public string Content
		{
			get { return _builder.ToString(); }
		}

		#region INotifyPropertyChanged Members
		public event PropertyChangedEventHandler PropertyChanged;
		#endregion

		public void Start()
		{
			CheckIfWasClosed();
			_builder.AppendLine("**************************");

			OnPropertyChanged("Content");
		}

		public void AddLine(string message)
		{
			CheckIfWasClosed();
			_builder.AppendLine(message);
			OnPropertyChanged("Content");
		}

		private void CheckIfWasClosed()
		{
			if (wasClosed)
			{
				_builder.Clear();
				wasClosed = false;
			}
		}

		public void AddRecieved(string message)
		{
			CheckIfWasClosed();
			_builder.AppendLine("Recieved:\t" + message);
			OnPropertyChanged("Content");
		}

		protected virtual void OnPropertyChanged(string propertyName)
		{
			PropertyChangedEventHandler handler = PropertyChanged;
			if (handler != null)
			{
				Deployment.Current.Dispatcher.BeginInvoke(() => handler(this, new PropertyChangedEventArgs(propertyName)));
			}
		}

		public bool WriteStatus(ResponseBase response)
		{
			CheckIfWasClosed();
			Start();
			AddLine("\tType:\t" + response.GetType());
			AddLine("\tSuccessfull:\t" + response.Successful);
			if (!response.Successful)
			{
				AddLine("\t\t!!!Error: ");
				AddLine(response.Error.Message);
				CloseLine();
				wasClosed = false;
			}
			else if (response is GetResponse)
			{
            AddLine("\tCOUNT: " +  ((GetResponse)response).Items.Count);
			}
		   AddLine("\t****\t***\t***");
			return response.Successful;
		}

		public void CloseLine()
		{
			_builder.AppendLine("\t\t***");
			wasClosed = true;
			OnPropertyChanged("Content");
		}

	   private string _message;
      /// <summary>
      /// For use in USING only
      /// </summary>
      public Tracer GetNew(string message)
      {
         this._message = message;
         AddLine("[BEGIN]:" + message);
         return this;
      }

	   #region Implementation of IDisposable
	   public void Dispose()
	   {
         AddLine("[END]:" + _message);
         AddLine(String.Empty);
	   }
	   #endregion
	}
}